package com.forum.action;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import sun.misc.BASE64Encoder;

import com.forum.dao.UserDAO;
import com.forum.pojo.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component("loginAction")
@Scope("prototype")
public class LoginAction extends ActionSupport{
	private User user;
	private String username;
	private String userpass;
	private UserDAO userDAO;
	
	/**
	 * 
	  * EncoderPwdByMd5 方法 
	  * <p>方法说明:</p> 
	  * @param str
	  * @return
	  * @throws NoSuchAlgorithmException
	  * @throws UnsupportedEncodingException 
	  * @return String 
	  * @author Evan 
	  * @date 2012-12-17
	 */
	public String EncoderPwdByMd5(String str) throws NoSuchAlgorithmException, 
	UnsupportedEncodingException { 
		// 确定计算方法 
		MessageDigest md5 = MessageDigest.getInstance("MD5"); 
		BASE64Encoder base64en = new BASE64Encoder(); 
		// 加密后的字符串 
		String newstr = base64en.encode(md5.digest(str.getBytes("utf-8"))); 
		return newstr; 
	} 
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String execute() throws Exception{
		ActionContext actionContext = ActionContext.getContext();
		Map session = actionContext.getSession();
		userpass = EncoderPwdByMd5(userpass);
		try {
			user = this.userDAO.queryUser(username, userpass);
			if(user.equals(null)){
			}else{
				session.put("UserName", user);
				return SUCCESS;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			session.put("UserName", "发生了异常！！！");
			return "exception";
		}
		session.put("UserName", null);
		
		return ERROR;
	}
	
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpass() {
		return userpass;
	}
	public void setUserpass(String userpass) {
		this.userpass = userpass;
	}
	public UserDAO getuserDAO() {
		return userDAO;
	}
	@Resource
	public void setuserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}
